﻿using ChuanYe.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;

namespace SJPlatForm.Web
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var container = new Microsoft.Practices.Unity.UnityContainer();
            DependencyRegisterType.Container_Sys(ref container);
            config.DependencyResolver = new UnityResolver(container);

            config.EnableCors();


            // Web API 配置和服务
            // Web API 路由
            // 1.默认 Web API 路由
            config.MapHttpAttributeRoutes();




            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //2.自定义路由一：匹配到action
            config.Routes.MapHttpRoute(
                name: "ActionApi",
                routeTemplate: "actionapi/{controller}/{action}/{id}",
                defaults: new { controller = "HelloWorld", action = "SayHello", id = RouteParameter.Optional }
            );

            //config.Routes.MapHttpRoute(
            // name: "HelloApi",
            // routeTemplate: "{controller}/{action}/{id}",
            // defaults: new { controller = "HelloWorld", action = "SayHello", id = RouteParameter.Optional });

            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

            //默认返回json
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "json", "application/json"));
            //返回格式选择 datatype 可以替换为任何参数 
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "xml", "application/xml"));

            //时间类型 utc->local
            var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            json.Indent = false;
            json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;


            //时间类型带TZ 转换
            config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IsoDateTimeConverter()
            {
                DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
            });
        }
    }
}
